package com.wg.system.service.impl;

import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wg.common.constant.Constants;
import com.wg.common.core.domain.PageQuery;
import com.wg.common.core.domain.TableDataInfo;
import com.wg.common.utils.AddressUtils;
import com.wg.common.utils.ServletUtils;
import com.wg.common.utils.StringUtils;
import com.wg.system.entity.SysLoginLog;
import com.wg.system.mapper.SysLoginLogMapper;
import com.wg.system.service.SysLoginLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 系统访问记录(SysLoginLog)服务实现类
 *
 * @author wg
 * @date 2022-04-24 00:12:52
 */
@Slf4j
@Service
public class SysLoginLogServiceImpl extends ServiceImpl<SysLoginLogMapper, SysLoginLog> implements SysLoginLogService {

    /**
     * 记录登录信息
     *
     * @param username 用户名
     * @param status   状态
     * @param message  消息
     * @param args     列表
     */
    @Async
    @Override
    public void recordLoginLog(String username, String status, String message, HttpServletRequest request, Object... args) {

        final UserAgent userAgent = UserAgentUtil.parse(request.getHeader("User-Agent"));
        final String ip = ServletUtils.getClientIP(request);

        String address = AddressUtils.getRealAddressByIP(ip);
        StringBuilder s = new StringBuilder();
        s.append(getBlock(ip));
        s.append(address);
        s.append(getBlock(username));
        s.append(getBlock(status));
        s.append(getBlock(message));
        // 打印信息到日志
        log.info(s.toString(), args);
        // 获取客户端操作系统
        String os = userAgent.getOs().getName();
        // 获取客户端浏览器
        String browser = userAgent.getBrowser().getName();
        // 封装对象
        SysLoginLog sysLoginLog = new SysLoginLog();
        sysLoginLog.setUserName(username);
        sysLoginLog.setIpaddr(ip);
        sysLoginLog.setLoginLocation(address);
        sysLoginLog.setBrowser(browser);
        sysLoginLog.setOs(os);
        sysLoginLog.setMsg(message);
        // 日志状态
        if (StringUtils.equalsAny(status, Constants.LOGIN_SUCCESS, Constants.LOGOUT, Constants.REGISTER)) {
            sysLoginLog.setStatus(Constants.SUCCESS);
        }
        if (Constants.LOGIN_FAIL.equals(status)) {
            sysLoginLog.setStatus(Constants.FAIL);
        }
        // 插入数据
        insertSysLoginLog(sysLoginLog);
    }

    private String getBlock(Object msg) {
        if (msg == null) {
            msg = "";
        }
        return "[" + msg.toString() + "]";
    }

    /**
     * 新增系统登录日志
     *
     * @param sysLoginLog 访问日志对象
     */
    @Override
    public void insertSysLoginLog(SysLoginLog sysLoginLog) {
        sysLoginLog.setLoginTime(new Date());
        baseMapper.insert(sysLoginLog);
    }

    @Override
    public TableDataInfo<SysLoginLog> selectPageLoginLogList(SysLoginLog loginLog, PageQuery pageQuery) {
        Map<String, Object> params = loginLog.getParams();
        LambdaQueryWrapper<SysLoginLog> lqw = new LambdaQueryWrapper<SysLoginLog>()
                .like(StringUtils.isNotBlank(loginLog.getIpaddr()), SysLoginLog::getIpaddr, loginLog.getIpaddr())
                .eq(StringUtils.isNotBlank(loginLog.getStatus()), SysLoginLog::getStatus, loginLog.getStatus())
                .like(StringUtils.isNotBlank(loginLog.getUserName()), SysLoginLog::getUserName, loginLog.getUserName())
                .between(params.get("beginTime") != null && params.get("endTime") != null,
                        SysLoginLog::getLoginTime, params.get("beginTime"), params.get("endTime"));
        if (StringUtils.isBlank(pageQuery.getOrderByColumn())) {
            pageQuery.setOrderByColumn("id");
            pageQuery.setIsAsc("desc");
        }
        Page<SysLoginLog> page = baseMapper.selectPage(pageQuery.build(), lqw);
        return TableDataInfo.build(page);
    }

    /**
     * 查询系统登录日志集合
     *
     * @param loginLog 访问日志对象
     * @return 登录记录集合
     */
    @Override
    public List<SysLoginLog> selectLoginLogList(SysLoginLog loginLog) {
        Map<String, Object> params = loginLog.getParams();
        return baseMapper.selectList(new LambdaQueryWrapper<SysLoginLog>()
                .like(StringUtils.isNotBlank(loginLog.getIpaddr()), SysLoginLog::getIpaddr, loginLog.getIpaddr())
                .eq(StringUtils.isNotBlank(loginLog.getStatus()), SysLoginLog::getStatus, loginLog.getStatus())
                .like(StringUtils.isNotBlank(loginLog.getUserName()), SysLoginLog::getUserName, loginLog.getUserName())
                .between(params.get("beginTime") != null && params.get("endTime") != null,
                        SysLoginLog::getLoginTime, params.get("beginTime"), params.get("endTime"))
                .orderByDesc(SysLoginLog::getId));
    }

    /**
     * 批量删除系统登录日志
     *
     * @param infoIds 需要删除的登录日志ID
     * @return 结果
     */
    @Override
    public int deleteLoginLogByIds(Long[] infoIds) {
        return baseMapper.deleteBatchIds(Arrays.asList(infoIds));
    }

    /**
     * 清空系统登录日志
     */
    @Override
    public void cleanLoginLog() {
        baseMapper.delete(new LambdaQueryWrapper<>());
    }
}

